package org.zjkoye.crm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.zjkoye.crm.common.Result;
import org.zjkoye.crm.entity.Usermain;
import org.zjkoye.crm.mapper.UsermainMapper;
import org.zjkoye.crm.service.UsermainService;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;

@Service
public class UsermainServiceImpl extends ServiceImpl<UsermainMapper, Usermain> implements UsermainService {

    @Autowired
    private UsermainMapper usermainMapper;

    @Autowired
    @Qualifier("threadPoolTaskExecutor")
    private Executor executor;

    @Async
    public CompletableFuture<Boolean> existsByUsername(String username) {
        return CompletableFuture.supplyAsync(() -> {
            LambdaQueryWrapper<Usermain> usermainQueryWrapper = new LambdaQueryWrapper<>();
            usermainQueryWrapper.eq(Usermain::getUsername, username);
            Long count = usermainMapper.selectCount(usermainQueryWrapper);
            return count > 0;
        }, executor);
    }

    @Async
    public CompletableFuture<Boolean> existsByEmail(String email) {
        return CompletableFuture.supplyAsync(() -> {
            LambdaQueryWrapper<Usermain> usermainQueryWrapper = new LambdaQueryWrapper<>();
            usermainQueryWrapper.eq(Usermain::getEmail, email);
            Long count = usermainMapper.selectCount(usermainQueryWrapper);
            return count > 0;
        }, executor);
    }

    @Async
    public CompletableFuture<Usermain> findByUsername(String username) {
        return CompletableFuture.supplyAsync(() -> {
            LambdaQueryWrapper<Usermain> usermainWrapper = new LambdaQueryWrapper<>();
            usermainWrapper.eq(Usermain::getUsername, username);
            return usermainMapper.selectOne(usermainWrapper);
        }, executor);
    }


    @Async
    public CompletableFuture<IPage<Usermain>> pageList(int pageSize, int currentPage, String name) {
        return CompletableFuture.supplyAsync(() -> {
            LambdaQueryWrapper<Usermain> wrapper = new LambdaQueryWrapper<>();
            wrapper.like(name != null && !"".equals(name), Usermain::getUsername, name);
            wrapper.eq(Usermain::getisdelete,0);
            IPage<Usermain> page = new Page<>(currentPage, pageSize);
            usermainMapper.selectPage(page, wrapper);
            return page;
        }, executor);
    }

    @Async
    public CompletableFuture<IPage<Usermain>> pagerecovery(int pageSize, int currentPage){
        return CompletableFuture.supplyAsync(() -> {
            LambdaQueryWrapper<Usermain> wrapper = new LambdaQueryWrapper<>();
            wrapper.like(Usermain::getisdelete, "1");
            IPage<Usermain> page = new Page<>(currentPage, pageSize);
            usermainMapper.selectPage(page, wrapper);
            return page;
        } , executor);
    }


    @Async
    public CompletableFuture<Result<String>> add(Usermain user) {


    // 检查登录名是否已存在
        return findByUsername(user.getUsername()).thenCompose(existingUser -> {
            if (existingUser != null) {
                return CompletableFuture.completedFuture(Result.error("登录名已存在，请重新输入"));
            }
            // 检查用户名是否为空
            if (user.getUsername() == null || user.getUsername().isEmpty()) {
                return CompletableFuture.completedFuture(Result.error("登录名不能为空"));
            }
            // 检查姓名是否为空
            if (user.getFullName() == null || user.getFullName().isEmpty()) {
                return CompletableFuture.completedFuture(Result.error("姓名不能为空"));
            }
            // 插入用户信息
            return CompletableFuture.supplyAsync(() -> {
                if (usermainMapper.insert(user) > 0) {
                    return Result.success("添加成功");
                }
                return Result.error("添加失败");
            }, executor);
        });
    }


    @Async
    public CompletableFuture<Boolean> updateUser(Usermain user) {
        return CompletableFuture.supplyAsync(() -> {
            LambdaUpdateWrapper<Usermain> wrapper = new LambdaUpdateWrapper<>();
            wrapper.set(true, Usermain::getRegionName, user.getRegionName())
                    .eq(Usermain::getUserId, user.getUserId());
            return usermainMapper.update(wrapper) > 0;
        }, executor);
    }

    @Async
    public CompletableFuture<Boolean> deleteById(int id) {
        return CompletableFuture.supplyAsync(() -> {
            LambdaUpdateWrapper<Usermain> wrapper = new LambdaUpdateWrapper<>();
            wrapper.set(true, Usermain::getisdelete, 1)
                    .eq(Usermain::getUserId, id);
            return usermainMapper.update(wrapper) > 0;
        }, executor);
    }

    @Async
    public CompletableFuture<Usermain> getUserById(int id) {
        return CompletableFuture.supplyAsync(() -> usermainMapper.selectById(id), executor);
    }

    @Async
    public CompletableFuture<Boolean> permission(int id) {
        return CompletableFuture.supplyAsync(() -> {
            Usermain user = usermainMapper.selectById(id);
            return "管理员".equals(user.getRole());
        }, executor);
    }

    @Override
    public void recovery(int id)
    {
        LambdaUpdateWrapper<Usermain> wrapper = new LambdaUpdateWrapper<>();
        wrapper.set(true, Usermain::getisdelete, 0)
                .eq(Usermain::getUserId, id);
        usermainMapper.update(wrapper);
    }

    @Override
    public void deleteforever(int id) {
        usermainMapper.deleteById(id);
    }
}
